package com.py.credit.service.impl;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.constant.SubjectTypConstant;
import com.py.credit.dao.DynamicSqlDao;
import com.py.credit.entity.Column;
import com.py.credit.entity.DynamicSqlEntity;
import com.py.credit.entity.Table;
import com.py.credit.service.ColumnService;
import com.py.credit.service.DynamicSqlService;
import com.py.credit.service.TableService;
import com.py.credit.service.excel.read.service.InspectDataStyleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DynamicSqlServiceImpl implements DynamicSqlService {
    @Autowired
    private DynamicSqlDao dynamicSqlDao;
    @Autowired
    private TableService tableServcie;
    @Autowired
    @Qualifier("default")
    private InspectDataStyleService inspectDataStyleService;
    @Autowired
    private ColumnService columnService;

    @Override
    public String insertTableInfo(Map<String, Object> params, String resourceId, String recordId, String mainName, String kId) {
        StringBuffer key = new StringBuffer();
        String tableName = "t_" + resourceId;
        List list = new ArrayList<>(20);
        //进行md5校验
        int tableId = tableServcie.getTableIdByResource(resourceId);
        List<Column> columns = columnService.getListByTableId(tableId);
        String message = inspectDataCheck(params, resourceId, tableId, columns);
        if (message != null) {
            return message;
        }
        //获取tybm
        Map<String, String> tybmParams = new HashMap<>(3);
        tybmParams.put("mainName", mainName);
        if (SubjectTypConstant.SUJECT_TYPE_FR.equals(kId)) {
            tybmParams.put("colmun", "A000001");
            tybmParams.put("tableName", "t_zoo_subject_unique_100000");
        }
        if (SubjectTypConstant.SUJECT_TYPE_ZRR.equals(kId)) {
            tybmParams.put("colmun", "B000001");
            tybmParams.put("tableName", "t_zoo_subject_unique_100001");
        }
        String tybm = dynamicSqlDao.selectTybmByMainName(tybmParams);

        //循环格式化字段准备入业务库
        for (Column column : columns) {
            //如果key存在
            if (params.containsKey(column.getMetricCode())) {
                String value = (String) params.get(column.getMetricCode());
                value = formatData(column, value);
                key.append(column.getMetricCode() + ",");
                list.add(value);
            }
        }
        key.append("tybm,MD5");
        list.add(tybm);
        list.add(params.get("MD5"));
        DynamicSqlEntity entity = new DynamicSqlEntity(tableName, key.toString(), list);
        try {
            dynamicSqlDao.insertTableInfo(entity);
            int id = entity.getId();
            if (SubjectTypConstant.SUJECT_TYPE_FR.equals(kId)) {
                dynamicSqlDao.backFillDataForFr(tableName, id, tybm);
            } else {
                dynamicSqlDao.backFillDataForZrr(tableName, id, tybm);
            }
        } catch (Exception e) {
            ExceptionLogger.error("DynamicSqlService#newInsertTableInfo", "动态入库失败！" + e.getMessage());
            return "动态入库失败！" + e.getMessage();
        }
        return null;
    }

    @Override
    public String updateTableInfo(Map<String, Object> params, String resourceId, String recordId) {
        List<Map<String, Object>> dataList = new ArrayList<>();


        int tableId = tableServcie.getTableIdByResource(resourceId);
        List<Column> columns = columnService.getListByTableId(tableId);
        String message = inspectDataCheck(params, resourceId, tableId, columns);
        if (message != null) {
            return message;
        }

        //循环拼接准备入库
        for (Column column : columns) {
            Map<String, Object> map = new HashMap<>(2);
            //如果key存在
            if (params.containsKey(column.getMetricCode())) {
                String value = (String) params.get(column.getMetricCode());
                value = formatData(column, value);
                map.put("key", column.getMetricCode());
                map.put("value", value);
                dataList.add(map);
            }
        }
        //单独增加md5
        Map<String, Object> md5Map = new HashMap<>(2);
        md5Map.put("key", "MD5");
        md5Map.put("value", params.get("MD5"));
        dataList.add(md5Map);
        dynamicSqlDao.updateTableInfo("t_" + resourceId, recordId, dataList);
        return null;
    }

    @Override
    public void deleteTableInfo(String resourceId, String recordId) {
        dynamicSqlDao.deleteTableInfo("t_" + resourceId, recordId);
    }

    @Override
    public LinkedHashMap<String, Object> selectTableInfoById(String tableId, String id, String mianName) {

        return dynamicSqlDao.selectTableInfoById(tableId, id, mianName);
    }

    @Override
    public List<LinkedHashMap<String, Object>> selectStyleByTableInfo(String tableId) {

        return dynamicSqlDao.selectStyleByTableInfo(tableId);
    }

    @Override
    public List<LinkedHashMap<String, Object>> selectIndexInfoByTybm(String relateSource, String tybm, String userId) {
        String[] ids = relateSource.split(",");
        List<LinkedHashMap<String, Object>> data = new ArrayList<>();
        String id = "";
        String metricId = "";
        List<LinkedHashMap<String, Object>> tableIds = dynamicSqlDao.selectTableIdById(ids);
        if (null != tableIds && tableIds.size() > 0) {
            for (int i = 0; i < tableIds.size(); i++) {
                id = "t_" + tableIds.get(i).get("resource_id");
                metricId = String.valueOf(tableIds.get(i).get("id"));
                List<LinkedHashMap<String, String>> metrics = dynamicSqlDao.selectMetricName(metricId);
                List<LinkedHashMap<String, Object>> tableInfo = dynamicSqlDao.selectIndexInfoByTybm(id, tybm);
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("isSql", tableInfo.size());
                map.put("name", (String) tableIds.get(i).get("resource_title"));
                map.put("head", metrics);
                map.put("data", tableInfo);
                data.add(map);
            }
            return data;
        }
        return null;
    }


    //格式化数据
    private String formatData(Column column, String value) {
        if ("".equals(value)) {
            value = null;
        }
        return value;
    }

    /**
     * 功能描述: 重复数据校验
     *
     * @param params     参数
     * @param resourceId 资源id
     * @return
     * @author YaoS
     * @date 19/5/6 18:58
     */
    private String inspectDataCheck(Map<String, Object> params, String resourceId, int tableId, List<Column> columns) {
        List<Map<String, Object>> listck = new ArrayList<>(1);
        listck.add(params);
        Table table = tableServcie.queryCubeById(tableId);
        //重复性校验
        Map<String, Object> duplicationCheck = inspectDataStyleService.duplicationCheck(listck, table, columns, false, true);
        String duplicationMess = String.valueOf(duplicationCheck.get("duplicationMess"));
        if (null != duplicationCheck && StringUtils.isNotEmpty(duplicationMess)) {
            return duplicationMess;
        }
        return null;
    }
}
